package cn.itcast.com.network.udp.vv;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class sendTask implements Runnable{
    //用于发送的socket对象
    private DatagramSocket sendSocket;
    //目标接收端的ip
    private InetAddress targetIp;
    //目标接收端的端口号
    private  int port;

    public sendTask(DatagramSocket sendSocket,String ipstr, int port) throws UnknownHostException {
        this.sendSocket = sendSocket;
        this.port = port;
        this.targetIp = InetAddress.getByName(ipstr);
    }

    @Override
    public void run() {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String data;
        try {
            while ((data = br.readLine())!=null){
            sendData(data);
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            sendSocket.close();
        }
    }

    private void sendData(String data) throws IOException {
        //将获得的数据转换成字节数组，方便待会的传参
        byte[] dataBytes = data.getBytes();
        //将参数都写入Packet中
        DatagramPacket datagramPacket = new DatagramPacket(dataBytes, 0, dataBytes.length, targetIp, port);

        sendSocket.send(datagramPacket);
    }
}
